package com.example.concurrentprogramming8016.CyclicBarrier;

import cn.hutool.core.lang.func.VoidFunc0;

import java.sql.Time;
import java.util.ArrayList;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.TimeUnit;

/**
 * @author liyanhao
 * @Date 2023-01-06 23:33
 */
public class CyclicBarrierDemo2 {
    //1.创建一个一组为3个的cb
    //2.创建一个线程池 多于三个，
    // 3.然后执行往map里边添加分数,并且添加完毕后就调用cb的await方法等待够一组后才开始执行cb的屏障回调方法
    private ArrayList<Integer> scores = new ArrayList<>(3);
    private CyclicBarrier cb = new CyclicBarrier(3, () -> {
        //执行计算平均数的方法
        int threeScore = 0;
        for (Integer score : scores) {
            System.out.print(score+"-");
            threeScore += score;
        }
        System.out.println("计算一组的平均数为:" + (threeScore / 3) + "分");
        System.out.println("计算完毕后清空list:");
        scores.clear();
    });

    public void count() throws InterruptedException {
        for (; ; ){
            new Thread(() -> {
                int score = (int) (Math.random() * 100);
                System.out.println("本次分数为:"+score);
                scores.add(score);
                try {
                    cb.await();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                } catch (BrokenBarrierException e) {
                    throw new RuntimeException(e);
                }
            }).start();
            System.out.print("创建一个数据休眠3秒-");
            TimeUnit.SECONDS.sleep(3);
        }



    }

    public static void main(String[] args) throws InterruptedException {
        CyclicBarrierDemo2 cyclicBarrierDemo2 = new CyclicBarrierDemo2();
        cyclicBarrierDemo2.count();
    }


}
